#include "IFUMap.h"
#include "IFUException.h"

#include <iostream>
#include <fstream>
#include <string>

#include <stdio.h>

using namespace std;

IFUMap::IFUMap(const string &filename) {

  this->filename = filename;
  read();
}

IFUMap::~IFUMap() {

  // deallocate fibBlock
  delete []fibBlock;

}

int IFUMap::getNFibers() {
  return nFibers;
}


int IFUMap::getNBlocks() {
  return nBlocks;
}


int IFUMap::getFibBlock(int block) {
  return fibBlock[block];
}

const string &IFUMap::getFilename() {
  return filename;
}

void IFUMap::read() {

  int block, blk , tot = 0;

  ifstream infile;
  infile.open(filename.c_str());

  if (!infile.is_open())
    throw IFUException("Error openning map: " + filename, "IFUMap");

  infile >> nFibers;
  infile >> nBlocks;

  fibBlock = new int[nBlocks];

  for (block=0 ; block < nBlocks; block++) {

    infile >> blk >> fibBlock[block] ;
  
    if (blk!=block)
      throw IFUException("Inconsistency in your MAP file: " + filename, "IFUMap");
  
    tot += fibBlock[block];

  }

  if ( tot != nFibers )
    throw IFUException("Inconsistency in MAP file: " + filename, "IFUMap");

  infile.close();

}

void IFUMap::dump() {

  cout << "fibers: " << nFibers << endl;
  cout << "blocks: " << nBlocks << endl;
    
  for (int i = 0; i < nBlocks; i ++)
    printf("block %2d: %2d\n", i, fibBlock[i]);

}
